# This file contains:
# -  Definition of the class Email used to store in the couchdb's database


import datetime
from couchdbkit import *
import dateconverter

import threading
import Queue
import time
import sys
import mailbox
import md5

# A class defining an email message to be stroed in couchdb database
class Email(Document):
    #documentType = "emailmessage"
    mailingList = StringProperty()
    sender = StringProperty()
    date = DateTimeProperty()
    subject = StringProperty()
    headers = ListProperty()
    text = StringProperty()

#    def __init__(self, mailingList, sender, date, headers, text):
        # used to construct the object
#        self.mailingList = mailingList
#        self.sender = sender
#        self.date = date
#        self.headers = headers
#        self.text = text

    def creator(self, mbox_email, mailingList):
        # method used to create an Email object
        # return the email object or none
        try:
            self.mailingList = mailingList
            self.sender = mbox_email['From'].decode('utf-8', 'replace')
            self.date = self.getDate(mbox_email)
            if not(self.date):
                return None
            self.subject = mbox_email['Subject'].decode('utf-8', 'replace')
            self.headers = [k+ ": "+v.decode('utf-8', 'replace') for (k,v) in mbox_email.items()]
            self.text = self.getText(mbox_email)
            self._id = str(self.date)+"&"+unicode(self.sender)+"&"+unicode(self.subject)
            m = md5.new()
            m.update(self._id)
            self._id = str(m.hexdigest())
            return self
        except:
            return None;
        
    def getText(self, mbox_email):
        # get the text form the mbox email
        payload = mbox_email.get_payload()
        if(isinstance(payload, str)):
            return payload.decode('utf-8', 'replace')
        else:
            text = ""
            for message in payload:
                text += self.getText(message)
            return text

    def getDate(self, mbox_email):
        # get the date form the mbox email
        return dateconverter.dateConverter(mbox_email['Date'])

    def addHeader(self, header):
        # add and header to the list, if it is a date or sender header it also adds it to the specific field
        if header.startswith("From:"):
            self.sender = unicode(header)
        if header.startswith("Date:"):
            #self.date = dateconverter.dateconverterDaynameDayMonthYear(header)
            self.date = dateconverter.dateConverter(header)
        if header.startswith("Subject:"):
            self.subject = unicode(header)
        self.headers.append(header)
		
    def addText(self, text):
        # add the text of the message
        self.text = unicode(text)

    def commitToDatabase(self, server, database):
        # save the current email to the given server and database
        self._id = str(self.date)+"&"+unicode(self.sender)+"&"+unicode(self.subject)
        m = md5.new()
        m.update(self._id)
        self._id = str(m.hexdigest())
        Email.set_db(database)
        try:
            self.save()
            return True
        except ResourceConflict:
            return False
        except:
            print "Unknown error while importing in database"
            return False
            

    def printMail(self):
        print "Date:" + str(self.date)
        print "Sender:" + str(self.sender)
        print "Mailing list:" + str(self.mailingList)
        print "Headers: \n" + str(self.headers)
        print "Body message:\n" + unicode(self.text)
        print "#################################################################################################################"

# END CLASS
def EmailCreator(mailinglist):
        # empty constructor
        return Email( mailingList=mailinglist, headers=[] )

